package com.deyuanyun.pic.settings.controller.greatwall;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.deyuanyun.pic.common.util.CommonUtil;
import com.deyuanyun.pic.common.util.StringUtils;
import com.deyuanyun.pic.settings.domain.base.Code;
import com.deyuanyun.pic.settings.domain.greatwall.ProductLogTempExpand;
import com.deyuanyun.pic.settings.domain.greatwall.ResponseResult;
import com.deyuanyun.pic.settings.enumeration.GreatwallCode;
import com.deyuanyun.pic.settings.service.base.CodeService;
import com.deyuanyun.pic.settings.service.greatwall.ProductLogTempService;
import com.github.pagehelper.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 *  日志管理controller,主要用于cs端日志获取，传未处理的日志到app等
 *  @author axiao(xj08.dream@gmail.com)
 *  @date 2016-12-21
 *  @version 1.0
 *  Histroy: [修改人][时间][描述]
 */
@Controller
@RequestMapping("/greatwall")
public class GWLogController {

    @Autowired
    ProductLogTempService productLogTempService;

    @Autowired
    CodeService codeService;

    /**
     * 保存cs端的日志
     * @param str
     * @return 
     * @author axiao(xj08.dream@gmail.com)
     * @date 2016-12-21
     */
    @RequestMapping(value = "/saveCs.json", method = RequestMethod.POST,
            consumes = FastJsonJsonView.DEFAULT_CONTENT_TYPE, produces = FastJsonJsonView.DEFAULT_CONTENT_TYPE)
    @ResponseBody
    public ResponseResult saveCsLog(@RequestBody String str) {
        ResponseResult result = new ResponseResult();
        try {
            ProductLogTempExpand productLogTemp = JSONObject.parseObject(str, ProductLogTempExpand.class);
            String sn =  productLogTemp.getSn();
            if(StringUtils.isEmpty(sn)) {
                throw new IllegalArgumentException("参数有误");
            }
            productLogTemp.setCreateDate(new Date());
            productLogTemp.setId(CommonUtil.getUUID());
            productLogTempService.insertSelective(productLogTemp);
            GreatwallCode code = GreatwallCode.SUCCESS;
            result.setCode(code.getCode()).setMsg(code.getLabel());
            Code co = codeService.getGwNCode(sn, "GW_K_TYPE_C");
            if(co != null) {
                result.setResult(responseK(sn, co.getCreateRemark(), co.getVersion()));
            }
        } catch (JSONException e) {
            GreatwallCode code = GreatwallCode.PARAMETER_FAIL;
            result.setCode(code.getCode()).setMsg(code.getLabel());
        } catch (IllegalArgumentException e) {
            GreatwallCode code = GreatwallCode.PARAMETER_FAIL;
            result.setCode(code.getCode()).setMsg(code.getLabel());
        } catch (Exception e) {
            GreatwallCode code = GreatwallCode.DATABASE_FAIL;
            result.setCode(code.getCode()).setMsg(code.getLabel());
        }
        return result;
    }

    private Map<String, Object> responseK(String sn, String publicKey, int version) {
        Map<String, Object> map = new HashMap<String, Object>(3);
        map.put("sn", org.apache.commons.lang.StringUtils.defaultIfEmpty(sn, ""));
        map.put("pk", org.apache.commons.lang.StringUtils.defaultIfEmpty(publicKey, ""));
        map.put("v", version);
        return map;
    }

    /**
     * 获取key
     * @param
     * @return
     * @author axiao(xj08.dream@gmail.com)
     * @date 2016-12-21
     */
    @RequestMapping(value = "/pk.json", method = RequestMethod.POST,
            consumes = FastJsonJsonView.DEFAULT_CONTENT_TYPE, produces = FastJsonJsonView.DEFAULT_CONTENT_TYPE)
    @ResponseBody
    public ResponseResult getK(@RequestBody String str) {
        ResponseResult result = new ResponseResult();
        try {
            String sn = JSONObject.parseObject(str).getString("sn");
            if(StringUtils.isNotEmpty(sn)) {
                GreatwallCode code = GreatwallCode.SUCCESS;
                result.setCode(code.getCode()).setMsg(code.getLabel());
                Code co = codeService.getGwNCode(sn, "GW_K_TYPE_C");
                if(co != null) {
                    result.setResult(responseK(sn, co.getCreateRemark(), co.getVersion()));
                }
            } else {
                GreatwallCode code = GreatwallCode.PARAMETER_FAIL;
                result.setCode(code.getCode()).setMsg(code.getLabel());
            }
        } catch (JSONException e) {
            GreatwallCode code = GreatwallCode.PARAMETER_FAIL;
            result.setCode(code.getCode()).setMsg(code.getLabel());
        }
        return result;
    }

    private ReentrantLock lock = new ReentrantLock();

    /**
     * app获取日志信息controller
     * @param
     * @return
     * @author axiao(xj08.dream@gmail.com)
     * @date 2016-12-21
     */
    @RequestMapping(value = "/l.json", method = RequestMethod.POST,
            consumes = FastJsonJsonView.DEFAULT_CONTENT_TYPE, produces = FastJsonJsonView.DEFAULT_CONTENT_TYPE)
    @ResponseBody
    public ResponseResult getLog(@RequestBody String str) {
        lock.lock();
        ResponseResult result = new ResponseResult();
        try {
            JSONObject jsonObject = JSONObject.parseObject(str);
            Integer pageSize =jsonObject.getInteger("s");
            Integer pageNo = jsonObject.getInteger("n");

            Page<ProductLogTempExpand> tempExpands = productLogTempService.queryUntreatedLogs(pageNo, pageSize);
            ProductLogTempExpand productLogTempExpand = null;
            List<String> dIds = new ArrayList<String>();
            for (int i = 0, len = tempExpands.size(); i < len; i++) {
                productLogTempExpand = tempExpands.get(i);
                dIds.add(productLogTempExpand.getId());
            }
            if(!dIds.isEmpty()) {
                productLogTempService.updateHandleByIds(dIds);
            }
            GreatwallCode code = GreatwallCode.SUCCESS;
            result.setCode(code.getCode()).setMsg(code.getLabel()).setResult(convertResult(tempExpands));
        } finally {
            lock.unlock();
        }
        return result;
    }

    private Map<String, Object> convertResult(Page<ProductLogTempExpand> tempExpands) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("n", tempExpands.getPageNum());
        map.put("s", tempExpands.getPageSize());
        map.put("t", tempExpands.getTotal());
        map.put("list", (List)tempExpands);
        return map;
    }

}
